﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PaperRenderingInterfaces;
using System.Net;
using System.IO;
using System.ComponentModel.Composition;

namespace PaperRenderingEngine
{
    /// <summary>
    /// Implements web access uniformly.
    /// </summary>
    [Export(typeof(IWebAccess))]
    public class WebAccess : IWebAccess
    {
        public string HTTPAgent = "DeepTalk Project";

        /// <summary>
        /// Fetch everything as a string. Blocking.
        /// Returns null if there is an error.
        /// </summary>
        /// <param name="whatToLoad"></param>
        /// <returns>Contents of web page, null if error</returns>
        public string GetUriAsString(Uri whatToLoad)
        {
            WebRequest req = WebRequest.Create(whatToLoad);
            ((HttpWebRequest)req).UserAgent = HTTPAgent;
            try
            {
                using (WebResponse resp = req.GetResponse())
                {
                    using (var stream = new StreamReader(resp.GetResponseStream()))
                    {
                        return stream.ReadToEnd();
                    }
                }
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// Return the time that the uri was last modified. Null if we can't
        /// figure it out.
        /// </summary>
        /// <param name="whatToCheck"></param>
        /// <returns></returns>
        public DateTime? GetLastModificationTime(Uri whatToCheck)
        {
            DateTime? result = GetLastModifiedTimeByMethod(whatToCheck, "HEAD");
            if (result.HasValue)
            {
                return result;
            }
            return GetLastModifiedTimeByMethod(whatToCheck, "GET");
        }

        /// <summary>
        /// Gets the date/time, by a particular method
        /// </summary>
        /// <param name="whatToCheck"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        private DateTime? GetLastModifiedTimeByMethod(Uri whatToCheck, string method)
        {
            WebRequest req = WebRequest.Create(whatToCheck);
            ((HttpWebRequest)req).UserAgent = HTTPAgent;
            ((HttpWebRequest)req).Method = method;
            try
            {
                using (WebResponse resp = req.GetResponse())
                {
                    string timeOfMod = resp.Headers["Last-Modified"];
                    if (timeOfMod != null)
                    {
                        return Convert.ToDateTime(timeOfMod);
                    }
                }
            }
            catch
            {
            }
            return null;
        }
    }
}
